package com.wmjsoft.plugins.security.handler

import com.wmjsoft.plugins.security.config.SecurityConfig
import com.wmjsoft.plugins.security.jwt.JwtSigner
import com.wmjsoft.plugins.security.user.CurrentUser
import com.wmjsoft.plugins.security.user.UserDetails
import net.cloudopt.next.web.Resource
import net.cloudopt.next.web.render.Template
import java.lang.Exception

class JwtAuth(var resource: Resource) {


    fun start() {
        if(ignore()) {
            auth()
        }
    }


    private fun ignore(): Boolean {
        val normalizedPath = resource.context.normalizedPath()
        if(SecurityConfig.ignorePath.indexOf(normalizedPath) >= 0) {
            return false
        }
        return true
    }

    private fun auth(){
        var auth = resource.request.headers()[SecurityConfig.headersKey]

        if(auth == null || auth.isBlank()){
            result("无权限访问",401)
        }
        if(!auth.startsWith(SecurityConfig.prefix)) {
            result("token 没有以${SecurityConfig.prefix}开头",401)
        }
        try {
            auth = auth.replace(SecurityConfig.prefix,"")
            val parseJWT = JwtSigner().parseJWT(auth)
            val currentUserId = parseJWT!!["id"]
            val currentUserName = parseJWT["username"]
            val userDetails = UserDetails(currentUserId as Long, currentUserName as String)
            CurrentUser.setCurrentUser(userDetails)
        }catch (e:Exception) {
            result("登录已过期,请重新登录",401)
        }


    }

    private fun result(msg:String,code:Int) {
        resource.response.statusCode = 401
        val template = Template()
        template.parameters["msg"] = msg
        template.parameters["code"] = code
        resource.renderJson{ template }
    }
}